<!-- 隐形订做配送 -->
<template>
  <div class="mod-config">
      <el-tabs type="border-card" @tab-click="tabChange" v-model="tabValue">
        <el-tab-pane label="未配送配镜单" name="tab1">
          <el-button-group style="margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-search" @click="searchHandle">查找</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
            <el-button type="primary" style="margin-left: 10px;" @click="shopSend" :loading="isSend">隐形配送并调拨到门店</el-button>
          </el-button-group>
          <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
            <el-form-item label="配镜单号">
              <el-input v-model="dataForm.saleBillId" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="取镜门店">
              <el-select v-model="dataForm.takeMirroDeptId" @change="takeMirroDeptIdChange">
                <el-option v-for="item in DeliveryDeptListOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="avue-crud" v-if="dataForm.takeMirroDeptId">
            <div class="avue-crud">
              <el-table :data="firstList" border v-loading="dataListLoading" :max-height="tableHeight1" @selection-change="selectionChangeHandle">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="saleBillId" label="配镜单号">
                  <template slot-scope="scope">
                    <el-button type="text" @click="checkDetailByOrder(scope.row.saleBillId)">{{scope.row.saleBillId}}</el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="customerName" label="顾客姓名"></el-table-column>
                <el-table-column prop="takeMirroDeptName" label="取镜门店"></el-table-column>
                <el-table-column prop="takeMirroTime" label="取镜时间"></el-table-column>
                <el-table-column prop="saleType" label="配镜类型">
                  <template slot-scope="scope">
                    <!-- 1-隐形订做,2-框镜订做,3-隐形成品,4-框镜成品,5-辅料-->
                    {{getSaleType(scope.row.saleType)}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="avue-crud__pagination">
              <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
              </el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已配送配镜单" name="tab2">
          <el-button-group style="margin-bottom: 10px;">
            <el-button type="primary" icon="el-icon-search" @click="searchHandle">查找</el-button>
            <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
          </el-button-group>
          <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
            <el-form-item label="配送单号">
              <el-input v-model="dataForm.deliverBillId" placeholder="请输入配送单号"></el-input>
            </el-form-item>
            <el-form-item label="配送日期">
              <el-row>
                <el-col :span="11">
                  <el-date-picker v-model="dataForm.deliveryTimeStart" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
                <el-col class="line" :span="2" style="text-align: center;">-</el-col>
                <el-col :span="11">
                  <el-date-picker v-model="dataForm.deliveryTimeEnd" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="配送人工号">
              <el-input v-model="dataForm.workNumber" placeholder="请输入配送人工号"></el-input>
            </el-form-item>
            <el-form-item label="配送类型">
              <el-checkbox-group v-model="dataForm.saleTypes">
                <el-checkbox label="4">框镜成品</el-checkbox>
                <el-checkbox label="2">框镜订制</el-checkbox>
                <el-checkbox label="1">隐形订制</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="取镜门店">
              <el-select v-model="dataForm.deptId" placeholder="请选择取镜门店">
                <el-option v-for="item in saleDeptOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="配镜单号">
              <el-input v-model="dataForm.saleBillId" placeholder="请输入配镜单号"></el-input>
            </el-form-item>
            <div>
              <el-form-item label="是否显示配送商品数量" label-width="160px">
                <el-checkbox v-model="dataForm.countShowFlag">显示</el-checkbox>
              </el-form-item>
            </div>
            <div v-if="this.dataForm.countShowFlag">
              <el-divider content-position="left">统计商品数量补充条件</el-divider>
              <el-form-item label="商品类别">
                <el-select v-model="dataForm.ctgId" @change="changeCtgId">
                  <el-option v-for="item in ctgOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="制造商">
                <el-input v-model="dataForm.supplyName">
                  <el-button slot="append" @click="openSupplyDialog">选择</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="配送商品品种" prop="brandName">
                <el-input v-model="dataForm.brandName">
                  <el-button slot="append" @click="getBrandList">选择</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="商品名称">
                <el-input v-model="dataForm.viewGoodsName"></el-input>
              </el-form-item>
            </div>
          </el-form>
          <div v-if="this.dataForm.countShowFlag">
            <el-row style="margin-bottom: 15px;">
              配送商品数量总计：{{ this.sum }}
            </el-row>
          </div>
          <div class="avue-crud">
            <el-table :data="secondList" border v-loading="dataListLoading" :max-height="tableHeight2">
              <el-table-column prop="deliverBillId" label="配送单号"></el-table-column>
              <el-table-column prop="deptName"label="取镜门店"> </el-table-column>
              <el-table-column prop="deliveryTime" label="配送时间"> </el-table-column>
              <el-table-column prop="userName" label="配送人"> </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button v-if="permissions.eims_delivery_edit" type="text" icon="el-icon-edit" @click="getInfoHandle(scope.row.id)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="avue-crud__pagination">
            <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="隐形配送并调拨到门店" :visible.sync="dialogShow" width="30%">
        <el-form ref="dataForm" :model="dataForm" :rules="dataRule">
          <el-form-item label="配送人员">
            <el-select v-model="dataForm.userId" placeholder="请选择" @change="userNameChange($event)" filterable
              default-first-option>
              <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
					<el-form-item label="供货商">
					  <el-select v-model="dataForm.supplierId" placeholder="请选择">
					    <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
					  </el-select>
					</el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="shopSendOrder" :loading="ischeck" v-prevent-re-click>确 定</el-button>
        </span>
      </el-dialog>

      <order-info v-if="infoVisible" ref="infoDialog"></order-info>
      <!-- 弹窗， 查看详情 -->
      <detail-dialog v-if="detailDialogVisible" ref="detailDialog"></detail-dialog>
      <!-- 弹窗，制造商选择 -->
      <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
      <!-- 弹窗，查询商品品种 -->
      <select-brand v-if="selectBrandVisible" ref="selectBrand" @refreshData="updateFormBrand"></select-brand>
  </div>
</template>

<script>
  import { filterParams } from '@/util/tools'
  import { remote } from '@/api/admin/dict'
  import {
    getInvisibleSaleByPage,
    getDeliveryByPage,
    addInvisibleDelivery,
    getNeedDeliveryDeptList,
    getGoodsNumberSum
  } from '@/api/eims/optician/delivery.js'
  import DetailDialog from './form'
  import { mapGetters } from 'vuex'
  import { getUserListNoRole } from '@/api/admin/user.js'
  import { getDeptInfoByDeptType } from "@/api/admin/dept";
  //弹窗，制造商选择
  import SearchSupply from '@/components/business/SearchSupply'
  import OrderInfo from '@/views/eims/optician/glassesinfo/detail'
  //弹窗，商品品种选择
  import SelectBrand from '../../storage/SearchBrand'
  import { getCtgList } from '@/api/eims/ctg'
  import {getSupplierInfoList} from '@/api/eims/supplier'
  import { getInfoParam } from '@/api/admin/sys-public-param'


  export default {
    data() {
      return {
        ischeck: false,
        isSend: false,
        dialogShow: false,
        supplyVisible: false,
        selectBrandVisible: false,
        infoVisible: false,
        ctgOptions: [],
        supplierOptions: [],
        saleTypeData: [],
        tabValue: 'tab1',
        dataForm: {
          userId: '',
          saleIdList: [],
          deliveryType: "2",
          saleTypes: [],
          deptId: '',
          takeMirroDeptId: '',
          userName: '',
          deptName: '',
          saleBillId: '',
          supplyName: '',
          brandName: '',
          supplierId: ''
        },
        flag: '',
        firstList: [],
        secondList: [],
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        dataListLoading: false,
        sum: '',
        selectionList: [],
        userOptions: [],
        saleDeptOptions: [],
        DeliveryDeptListOptions: [],
        detailDialogVisible: false, // 查看信息
        dataRule: {
          userId: [{
            required: true,
            message: '配送人不能为空'
          }]
        }
      }
    },
    components: {
      DetailDialog,
      SearchSupply,
      SelectBrand,
      OrderInfo
    },
    created() {
      this.getTakeMirroDeptList()
      this.getDeptList()
      this.getGoodsCtgList()
      this.getSupplierList()
      remote('sale_type').then(result => {
        this.saleTypeData = result.data.data
      })
    },
    computed: {
      ...mapGetters(['permissions', 'userInfo', 'bizData']),
      tableHeight1: function(){
        return window.innerHeight - 260
      },
      tableHeight2: function(){
        return window.innerHeight - 260
      }
    },
    methods: {
      //  查询数据
      searchHandle() {
        this.pageIndex = 1
        this.getDataList()
      },
      tabChange(data) {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
          if (key == 'saleTypes') {
            this.dataForm[key] = []
          }
        }
        this.firstList = []
        this.secondList = []
        this.pageIndex = 1
        this.pageSize = 10
        this.getDataList()
      },
      // 取镜部门change事件
      takeMirroDeptIdChange(val) {
        this.getDataList()
      },
      //  查看配镜单详情
      checkDetailByOrder(order) {
        this.infoVisible = true;
        this.$nextTick(() => {
          this.$refs.infoDialog.init('', order, '配镜单详情');
        });
      },
      // 获取数据列表
      getDataList() {
        //未配送
        this.dataListLoading = true
        if (this.tabValue == 'tab1') {
          let params1 = {
            current: this.pageIndex,
            size: this.pageSize
          }
          let params2 = filterParams(this.dataForm)
          this.getUserList()
          getInvisibleSaleByPage(Object.assign(params1, params2)).then(response => {
            if(response.data.code == '0'){
              this.firstList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
        } else if (this.tabValue == 'tab2') {
          let params1 = {
            current: this.pageIndex,
            size: this.pageSize,
            deliveryType: '2'
          }
          let params2 = filterParams(this.dataForm)

          getDeliveryByPage(Object.assign(params1, params2)).then(response => {
            if(response.data.code == '0'){
              this.secondList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
          if (this.dataForm.countShowFlag) {
            getGoodsNumberSum(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.sum = response.data.data
              }else{
                this.$message.error(response.data.msg)
              }
            })
          }
        }

      },
      // 每页数据条数变化事件
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页改变事件
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 查看
      getInfoHandle(id) {
        this.detailDialogVisible = true
        this.$nextTick(() => {
          this.$refs.detailDialog.init(id)
        })
      },
      //获取配镜类型枚举
      getSaleType: function(value) {
        let obj = {};
        obj = this.saleTypeData.find((item) => {
          return item.value == value;
        });
        return obj.label;
      },
			//获取供货商列表
			getSupplierList(){
			  getSupplierInfoList().then(response =>{
          if(response.data.code == '0'){
            this.supplierOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
			  })
			},
      // 搜索清空
      searchReset() {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
          if (key == 'saleTypes') {
            this.dataForm[key] = []
          }
        }
      },
      handleSearchShow() {
        this.searchShow = !this.searchShow;
      },
      // 多选表格change事件
      selectionChangeHandle(val) {
        this.selectionList = val
      },

      // 获取员工用户列表
      getUserList(id) {
        getUserListNoRole().then(response => {
          if(response.data.code == '0'){
            let resultData = response.data.data
            let userList = []
            resultData.forEach(item => {
              let userObj = {
                value: item.id,
                label: item.realName + '-' + item.username
              }
              userList.push(userObj)
            })
            this.userOptions = userList
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      userNameChange($event) {
        this.userOptions.forEach(item => {
          if (item.value == $event) {
            this.dataForm.userName = item.label
          }
        })
      },
      //判断门店上游供货商是否必填标志
      getFlag(){
        getInfoParam('SUPPLIER_STATUS',2,this.userInfo.unitId).then(result => {
          this.flag = result.data.data.publicValue
          this.flag = (this.flag == 'true') ? true : false
        })
      },
      //弹框
      shopSend() {
        this.isSend = true
        if (this.selectionList.length) {
          this.getFlag()
          this.dialogShow = true
        } else {
          this.isSend = false
          this.$message.warning('请选择配镜单')
        }
      },
      //点击门店配送接口
      shopSendOrder() {
        this.dataForm.saleIdList = [];
        let ids = []
        if(this.flag){
          if(this.dataForm.supplierId == 0){
            this.isSend = false
            this.$message.warning('请选择供货商')
            return false
          }
        }
        this.selectionList.forEach(item => {
          ids.push(item.saleId)
        })
        this.dataForm.saleIdList = ids;
        this.dataForm.deptId = this.dataForm.takeMirroDeptId;
        this.ischeck = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addInvisibleDelivery(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.$message.success("配送成功")
                this.dialogShow = false
                this.getDataList()
              }else{
                this.$message.error(response.data.msg)
              }
              this.isSend = false
              this.ischeck = false
            }).catch(() => {
              this.isSend = false
              this.ischeck = false
            })
          } else {
            this.isSend = false
            this.ischeck = false
          }
        })


      },
      // 获取取镜门店列表
      getTakeMirroDeptList() {
        getNeedDeliveryDeptList({
          deliveryType: '2'
        }).then(result => {
          let resultData = result.data.data
          let list = []
          resultData.forEach(item => {
            list.push({
              value: item.id,
              label: item.name
            })
          })
          this.DeliveryDeptListOptions = list
        })
      },
      //获取取镜部门列表tab2
      getDeptList() {
        getDeptInfoByDeptType(1).then(response => {
          this.saleDeptOptions = response.data.data;
        });
      },
      //  获取商品类别
      getGoodsCtgList() {
        getCtgList().then(result => {
          this.ctgOptions = result.data.data
        })
      },
      changeCtgId() {
        this.dataForm.supplyId = ''
        this.dataForm.supplyName = ''
        this.dataForm.brandId = ''
        this.dataForm.brandName = ''
      },
      //  打开选择制造商弹窗
      openSupplyDialog() {
        let data = {
          ctgId: this.dataForm.ctgId
        }
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(data)
        })
      },
      getSupplyData(data) {
        this.$set(this.dataForm, 'supplyId', data.id)
        this.$set(this.dataForm, 'supplyName', data.name)
        this.dataForm.brandId = ''
        this.dataForm.brandName = ''
      },
      // 获取商品品种信息
      getBrandList() {
        if (!this.dataForm.ctgId) {
          this.$message.warning('请选择商品类别')
          return false
        }
        if (!this.dataForm.supplyId) {
          this.$message.warning('请选择制造商')
          return false
        }
        let data = {
          ctgId: this.dataForm.ctgId,
          supplyId: this.dataForm.supplyId
        }
        this.selectBrandVisible = true
        this.$nextTick(() => {
          this.$refs.selectBrand.init(data)
        })
      },
      //  更新表单品种信息
      updateFormBrand(data) {
        console.log(data)
        this.dataForm.brandId = data.id
        this.dataForm.brandName = data.name
        this.dataForm.brandCode = data.code
        this.dataForm.name = data.name
        this.dataForm.unitType = data.unitType
      },

    }
  }
</script>
